/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package models;

import java.util.List;
import java.util.Map;
import javax.persistence.Entity;
import play.data.validation.Required;
import play.db.jpa.Model;

/**
 *
 * @author alex
 */

@Entity
public class Tag extends Model implements Comparable<Tag>{

    @Required
    public String name;
    
    public Tag(String name) {
        this.name = name;
    }
    
    public String toString(){
        return name;
    }
    
    public int compareTo(Tag otherTag) {
        return name.compareTo(otherTag.name);
    }
    
    public static Tag findOrCreateByName(String name){
    Tag tag = Tag.find("byName", name).first();
    if(tag==null){
        tag = new Tag(name);
    }
    return tag;
    }
    
    public static List<Map> getCloud(){
        List<Map> result = Tag.find(
            "select new map(t.name as tag,"
                    + " count(p.id) as pound)"
                    + " from Post p join p.tags as t"
                    + " group by t.name order by "
                    + "t.name").fetch();
        return result;
}
   
    
    
}
